package com.hzdesk.media.koreabatchmatvector.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.hzdesk.media.koreabatchmatvector.bean.RequestUploadFileCallBackBean;
import com.hzdesk.media.koreabatchmatvector.bean.UploadBean;
import com.hzdesk.media.koreabatchmatvector.bean.UploadFileTokenBean;
import com.hzdesk.media.koreabatchmatvector.bean.VideoFile;
import com.hzdesk.media.koreabatchmatvector.config.AppConfig;
import com.hzdesk.media.koreabatchmatvector.config.RBConfig;
import com.hzdesk.media.koreabatchmatvector.dao.VideoFileDaoUtils;
import com.hzdesk.media.koreabatchmatvector.request.RequestAction;
import com.hzdesk.media.koreabatchmatvector.request.UploadFileCallBackRequest;
import com.hzdesk.media.koreabatchmatvector.utils.DesUtils;
import com.hzdesk.media.koreabatchmatvector.utils.FileUtil;
import com.hzdesk.media.koreabatchmatvector.utils.JsonUitl;
import com.upyun.library.common.Params;
import com.upyun.library.common.ResumeUploader;
import com.upyun.library.common.UploadEngine;
import com.upyun.library.listener.UpCompleteListener;
import com.upyun.library.listener.UpProgressListener;
import com.upyun.library.utils.UpYunUtils;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 上传文件服务
 * Created by Administrator on 2018/5/26.
 */

public class UpLoadFileService extends Service {
    private static final String TAG = UpLoadFileService.class.getSimpleName();
    private UploadBinder uploadBinder = new UploadBinder();
    private ResumeUploader uploader;
    private getUploadProgress getUploadProgress;
    private UploadFileTokenBean uploadFileTokenBean;
    private UploadBean uploadBean;
    private VideoFile videoFile;
    List<String> list_file = new ArrayList<>();
    List<String> list_url = new ArrayList<>();
    List<String> list_type = new ArrayList<>();
    private int index = 0;
    //上传完成标识
    private boolean isUploadSuccess = false;
    //空间名
    public static String SPACE = "klptest";
    //操作员
    public static String OPERATER = "klpadmin";
    //密码
    public static String PASSWORD = "klpadmin123";


    VideoFileDaoUtils videoFileDaoUtils;


    @Override
    public IBinder onBind(Intent intent) {
        return uploadBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        videoFileDaoUtils = new VideoFileDaoUtils(UpLoadFileService.this);
    }

    public class UploadBinder extends Binder {
        public UpLoadFileService getService() {
            return UpLoadFileService.this;
        }
    }

    public void setGetUploadProgress(UpLoadFileService.getUploadProgress getUploadProgress) {
        this.getUploadProgress = getUploadProgress;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    public void startUpload(UploadFileTokenBean uploadFileTokenBean, UploadBean uploadBean, VideoFile videoFile) {
        Log.d(TAG, uploadFileTokenBean.toString());
        this.uploadFileTokenBean = uploadFileTokenBean;
        this.uploadBean = uploadBean;
        this.videoFile = videoFile;
        try {
            DesUtils desUtils=new DesUtils();
            Log.e(TAG, desUtils.encrypt(OPERATER));
        } catch (Exception e) {
            e.printStackTrace();
        }

        //批注文件
        list_file.add(videoFile.getPath() + "/" + videoFile.getRealname() + AppConfig.FILE_TYPE_XML);
        //视频文件
        list_file.add(videoFile.getPath() + "/" + videoFile.getRealname() + AppConfig.FILE_TYPE_MP4);
        //音频文件
        list_file.add(videoFile.getPath() + "/" + videoFile.getRealname() + AppConfig.FILE_TYPE_AMR);
        //水印文件
        list_file.add(videoFile.getPath() + "/" + videoFile.getRealname() + AppConfig.FILE_TYPE_PNG);
        //缩略图
        list_file.add(videoFile.getPath() + "/" + videoFile.getRealname() + AppConfig.FILE_TYPE_JPG);

        list_url.add("/" + uploadBean.getFileUrl() + "/" + videoFile.getSecondname() + AppConfig.FILE_TYPE_XML);
        list_url.add("/" + uploadBean.getFileUrl() + "/" + videoFile.getSecondname() + AppConfig.FILE_TYPE_MP4);
        list_url.add("/" + uploadBean.getFileUrl() + "/" + videoFile.getSecondname() + AppConfig.FILE_TYPE_AMR);
        list_url.add("/" + uploadBean.getFileUrl() + "/" + videoFile.getSecondname() + AppConfig.FILE_TYPE_PNG);
        list_url.add("/" + uploadBean.getFileUrl() + "/" + videoFile.getSecondname() + AppConfig.FILE_TYPE_JPG);

        list_type.add(AppConfig.FILE_TYPE_XML);
        list_type.add(AppConfig.FILE_TYPE_MP4);
        list_type.add(AppConfig.FILE_TYPE_AMR);
        list_type.add(AppConfig.FILE_TYPE_PNG);
        list_type.add(AppConfig.FILE_TYPE_JPG);

        uploadSmallFile();
        try {
            upLoad();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 结束上传
     */
    public void stopUpload() {
        if (!isUploadSuccess) {

        }

    }

    /**
     * 上传完成
     */
    private void successUpload() {
        isUploadSuccess = true;
        RequestUploadFileCallBackBean requestUploadFileCallBackBean = new RequestUploadFileCallBackBean(uploadFileTokenBean.getData().getId(), 1, 0);
        UploadFileCallBackRequest request = new UploadFileCallBackRequest(this, RBConfig.HOST_IP + RequestAction.getAfterUploadFile());
        request.setOnUploadFileCallBackListener(onUploadFileCallBackListener);
        request.setRequestBody(JsonUitl.objectToString(requestUploadFileCallBackBean));

    }

    /**
     * 上传文件到云端（断点续传）
     *
     * @throws JSONException
     */
    private void upLoad() throws JSONException {

        for (int i = 0; i < list_file.size(); i++) {
            String filename = list_file.get(i);
            if (filename.endsWith(AppConfig.FILE_TYPE_MP4)) {
                if (FileUtil.isFileExist(list_file.get(i))) {
                    final File file = new File(list_file.get(i));
                    final ResumeUploader uploader = new ResumeUploader(SPACE, OPERATER, UpYunUtils.md5(PASSWORD));
                    //设置 MD5 校验
                    uploader.setCheckMD5(true);
                    uploader.setOnProgressListener(new UpProgressListener() {
                        @Override
                        public void onRequestProgress(long bytesWrite, long contentLength) {
                            float progress = (float) bytesWrite / contentLength * 100;
                            Log.d(TAG, progress + "");
                            getUploadProgress.getProgress((int) progress);
                            videoFile.setProgress((int) progress);
                            videoFileDaoUtils.updateVideoFile(videoFile);
                        }
                    });
                    Map<String, Object> processParam = new HashMap<String, Object>();

                    processParam.put(ResumeUploader.Params.BUCKET_NAME, SPACE);
                    processParam.put(ResumeUploader.Params.NOTIFY_URL, "http://httpbin.org/post");
                    processParam.put(ResumeUploader.Params.ACCEPT, "json");
                    processParam.put(ResumeUploader.Params.SOURCE, list_url.get(1));

                    JSONArray array = new JSONArray();

                    processParam.put(ResumeUploader.Params.TASKS, array);
                    final UpCompleteListener completeListener = new UpCompleteListener() {
                        @Override
                        public void onComplete(boolean isSuccess, String result) {
                            getUploadProgress.succcess();
                            successUpload();
                        }
                    };
                    Log.d(TAG, list_url.get(i));

                    uploader.upload(file, list_url.get(i), null, processParam, completeListener);

                }
            }
        }


    }

    /**
     * 上传文件到云端（小文件）
     */
    private void uploadSmallFile() {
        for (int i = 0; i < list_file.size(); i++) {
            String file = list_file.get(i);
            //视频文件使用断点续传
            if (file.endsWith(AppConfig.FILE_TYPE_MP4)) {
                continue;
            }
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put(Params.BUCKET, SPACE);
            paramsMap.put(Params.SAVE_KEY, list_url.get(i));
            paramsMap.put(Params.RETURN_URL, "httpbin.org/post");
            final int finalI = i;
            UpProgressListener progressListener = new UpProgressListener() {
                @Override
                public void onRequestProgress(final long bytesWrite, final long contentLength) {
                    Log.e(TAG, list_type.get(finalI)+":"+(100 * bytesWrite) / contentLength + "%");

                }
            };
            //结束回调，不可为空
            UpCompleteListener completeListener = new UpCompleteListener() {
                @Override
                public void onComplete(boolean isSuccess, String result) {
                    Log.e(TAG, list_type.get(finalI)+":"+isSuccess + ":" + result);
                }
            };

            //表单上传（本地签名方式）
            UploadEngine.getInstance().formUpload(new File(list_file.get(i)), paramsMap, OPERATER, UpYunUtils.md5(PASSWORD), completeListener, progressListener);

        }


    }

    UploadFileCallBackRequest.OnUploadFileCallBackListener onUploadFileCallBackListener = new UploadFileCallBackRequest.OnUploadFileCallBackListener() {
        @Override
        public void success() {
            //更改数据库文件
            VideoFileDaoUtils videoFileDaoUtils = new VideoFileDaoUtils(UpLoadFileService.this);
            videoFile.setIsUpload(true);
            videoFile.setProgress(100);
            videoFileDaoUtils.updateVideoFile(videoFile);
        }

        @Override
        public void fail(String s) {

        }
    };


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 上传进度回调
     */
    public static interface getUploadProgress {
        void getProgress(int num);

        void succcess();

        void pause();

        void stop();
    }
}
